<!DOCTYPE html>
<html>
  <head>
    <title>SSE Test</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h3>消息记录：</h3>
    <pre id="messages"></pre>

    <script>
      const messagesDiv = document.getElementById("messages");
      let currentMessage = "";
      let isNewParagraph = true;

      function appendMessage(text) {
        messagesDiv.textContent += text + "\n";
        console.log("收到数据:", text);
      }

      function shouldSendMessage(content) {
        if (/[。！？.!?]\n\n$/.test(currentMessage)) {
          return true;
        }
        if (/[。！？.!?]$/.test(content) && currentMessage.length > 10) {
          return true;
        }
        return false;
      }

      function processMessage(data) {
        // 处理不同类型的消息
        switch (data.type) {
          case "answer":
            if (data.content.startsWith("《") && currentMessage === "") {
              appendMessage(data.content);
              return;
            }

            if (isNewParagraph && data.content.trim()) {
              currentMessage += "\n";
              isNewParagraph = false;
            }

            currentMessage += data.content;

            if (shouldSendMessage(data.content)) {
              appendMessage(currentMessage.trim());
              currentMessage = "";
              isNewParagraph = true;
            }
            break;

          case "follow_up":
            appendMessage("建议问题: " + data.content);
            break;

          case "verbose":
            // 可以选择是否显示详细信息
            console.log("详细信息:", data.content);
            break;

          default:
            // 其他类型的消息直接显示内容
            if (data.content) {
              appendMessage("收到数据: " + data.content);
            }
        }
      }

      function connect() {
        // var url = 'https://e.zhoong.cn/test-coze/api/v1/chat/create';
        var url = "http://127.0.0.1:9531/api/v1/chat/create";
        fetch(url, {
          method: "POST",
          headers: {
            Authorization: "Bearer CxsdUvGjHAjmqjJ08vv7FQ==",
            Accept: "text/event-stream",
          },
          body: JSON.stringify({
            conversation_id: "7473401520781017103",
            message: "具体细节就不知道了,反正哭的老惨了",
          }),
        })
          .then((response) => {
            const reader = response.body.getReader();
            let decoder = new TextDecoder("utf-8", {
              fatal: true,
              ignoreBOM: true,
            });
            let buffer = "";

            function readStream() {
              reader
                .read()
                .then(({ done, value }) => {
                  if (done) {
                    if (currentMessage) {
                      appendMessage(currentMessage);
                    }
                    return;
                  }

                  try {
                    buffer += decoder.decode(value, { stream: true });
                  } catch (e) {
                    decoder = new TextDecoder("utf-8", {
                      fatal: true,
                      ignoreBOM: true,
                    });
                    buffer += decoder.decode(value);
                  }

                  const lines = buffer.split("\n\n");
                  buffer = lines.pop() || "";

                  lines.forEach((line) => {
                    if (line.startsWith("data:")) {
                      const jsonStr = line.slice(5).trim();
                      try {
                        const data = JSON.parse(jsonStr);
                        processMessage(data);
                      } catch (e) {
                        console.error("解析错误:", e);
                      }
                    }
                  });

                  readStream();
                })
                .catch((error) => {
                  console.error("读取错误:", error);
                });
            }

            readStream();
          })
          .catch((error) => {
            console.error("连接错误:", error);
          });
      }

      // 启动连接
      connect();
    </script>
  </body>
</html>
